package com.villaday.idf.fragment;

import android.graphics.Color;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.view.View;


import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.R;
import com.villaday.idf.base.BaseFragment;
import com.villaday.idf.custom.CustomMarkerView;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.model.statProfitsEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.DateUtils;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;


public class ChartVPFragment extends BaseFragment implements OkHttpUtil.OnDataListener {

    @BindView(R.id.spread_line_chart)
    public LineChart mLineChart;
    @BindView(R.id.srf_home)
    public SwipeRefreshLayout srl;


    private Gson gson = new GsonBuilder().create();
    private LoadingDialog loadingDialog;
    private String type = "month";//week
    private String year = "2018";
    private String month = "";
    //设置X轴Y轴
    List<Entry> entries = new ArrayList<>();

    YAxis leftAxis;


    public static ChartVPFragment newInstance() {
        return new ChartVPFragment();
    }

    @Override
    protected int getViewResId() {
        //  ShareSDK.initSDK(getActivity());
        return R.layout.fragment_chart;
    }

    @Override
    protected void init(View v) {
        loadingDialog = LoadingDialog.newInstance("加载中...");
        loadingDialog.show(getActivity().getFragmentManager());
        year=DateUtils.getYear() + "";
        mLineChart.setNoDataText("");
    }

    @Override
    protected void loadData() {
        Map<String, String> map = new HashMap<>();
        map.put("type", type);
        map.put("year", year + "");
//        map.put("month", month);
        OkHttpUtil.getJSON(getActivity(), Constant.URL.stat_profits, map, this);

    }


    @Override
    public void onResponse(String url, String json) {
        if (Constant.URL.stat_profits.equals(url)) {
            LogeUtil.e("stat_profits", json);
            dismissLoading();
            statProfitsEntity recommendEntity = gson.fromJson(json, statProfitsEntity.class);
            if ("200".equals(recommendEntity.getCode())) {
                entries.clear();
                if (recommendEntity.getBody() != null) {
                    boolean isReset =false;
                    for (int i = 0; i < recommendEntity.getBody().getList().size(); i++) {
                        if(recommendEntity.getBody().getList().get(i).getAmounts()>0)
                            isReset = true;
                        entries.add(new Entry(i, recommendEntity.getBody().getList().get(i).getAmounts()));
                    }

                    initData(entries);
                    if(!isReset){
                        leftAxis.setAxisMaximum(100f);
                    }else{
                        leftAxis.resetAxisMaximum();
                    }
                } else {
                    mLineChart.clear();
                    for (int i = 0; i < 12; i++) {
                        entries.add(new Entry(i, 0));
                    }
                    voidData(entries);
                }

            }

        }
    }

    @Override
    public void onFailure(String url, String error) {

    }


    private void dismissLoading() {

        if (srl != null && srl.isRefreshing()) {
            srl.setRefreshing(false);
        }
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }

    }

    public void initData(List<Entry> entries) {

        //把数据赋值到你的线条
        mLineChart.clear();
        //mLineChart.getData().getDataSetCount();获取圆点
        LineDataSet dataSet = new LineDataSet(entries, "Label"); // add entries to dataset
        dataSet.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
        dataSet.setDrawCircleHole(false);
//        dataSet.setCubicIntensity(0.2f);
        dataSet.setColor(getResources().getColor(R.color.colorYellow));
        dataSet.setHighLightColor(getResources().getColor(R.color.colorYellow));//设置点击交点后显示交高亮线的颜色
        dataSet.setHighlightEnabled(true);//是否使用点击高亮线
        dataSet.setValueTextColor(Color.WHITE);
        dataSet.setLineWidth(3f);//设置线宽
        dataSet.setCircleRadius(2f);//设置焦点圆心的大小
        dataSet.setHighlightLineWidth(0.5f);//设置点击交点后显示高亮线宽
        dataSet.enableDashedHighlightLine(10f, 5f, 0f);//点击后的高亮线的显示样式
        dataSet.setValueTextSize(12f);//设置显示值的文字大小
        dataSet.setDrawFilled(false);//设置使用 范围背景填充
        dataSet.setDrawValues(false);
        dataSet.setDrawCircles(false);
        dataSet.setCircleRadius(5f);//设置外圈圆半径
        dataSet.setCircleColor(getResources().getColor(R.color.colorYellow));//设置外圈圆颜色
        dataSet.setCircleHoleRadius(4f);//设置内圈圆半径
        dataSet.setCircleColorHole(getResources().getColor(R.color.colorWhite));//设置内圈圆颜色
        mLineChart.setScaleXEnabled(false);
        mLineChart.setScaleYEnabled(false);
        CustomMarkerView mv = new CustomMarkerView(getActivity(), R.layout.item_markview);
        mv.setChartView(mLineChart);
        mLineChart.setMarker(mv);


        //X轴与Y轴的样式
        //设置样式
        YAxis rightAxis = mLineChart.getAxisRight();

        //设置图表右边的y轴禁用
        rightAxis.setEnabled(false);
        leftAxis = mLineChart.getAxisLeft();
        //设置图表左边的y轴禁用
        leftAxis.setEnabled(false);


        //设置x轴
        XAxis xAxis = mLineChart.getXAxis();
        xAxis.setTextColor(Color.parseColor("#333333"));
        xAxis.setTextSize(11f);
        xAxis.setAxisMinimum(0f);
        xAxis.setDrawAxisLine(true);//是否绘制轴线
        xAxis.setDrawGridLines(false);//设置x轴上每个点对应的线
        xAxis.setDrawLabels(true);//绘制标签  指x轴上的对应数值
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置x轴的显示位置
        xAxis.setGranularity(1f);//禁止放大后x轴标签重绘
        xAxis.setLabelCount(12, true);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return String.valueOf((int) value + 1).concat("月");
            }

            @Override
            public int getDecimalDigits() {
                return 0;
            }
        });

        /**
         * 透明化图例
         */
        Legend legend = mLineChart.getLegend();
        legend.setForm(Legend.LegendForm.NONE);
        legend.setTextColor(Color.WHITE);

        /**
         * 隐藏x轴描述
         */
        Description description = new Description();
        description.setEnabled(false);
        mLineChart.setDescription(description);


        //设置数据，刷新列表
        LineData lineData = new LineData(dataSet);
        //是否绘制线条上的文字
        lineData.setDrawValues(false);
        mLineChart.setData(lineData);
        mLineChart.invalidate(); // refresh

    }


    public void onRefresh() {
        loadData();
    }

    public void onRefresh(String year) {
        this.year = year;
        loadData();
    }


    public void voidData(List<Entry> entries) {

        //把数据赋值到你的线条
        mLineChart.clear();
        //mLineChart.getData().getDataSetCount();获取圆点
        LineDataSet dataSet = new LineDataSet(entries, "Label"); // add entries to dataset
        dataSet.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
        dataSet.setDrawCircleHole(false);
//        dataSet.setCubicIntensity(0.2f);
        dataSet.setColor(Color.TRANSPARENT);
        dataSet.setHighLightColor(getResources().getColor(R.color.colorYellow));//设置点击交点后显示交高亮线的颜色
        dataSet.setHighlightEnabled(false);//是否使用点击高亮线
        dataSet.setValueTextColor(Color.WHITE);
        dataSet.setLineWidth(3.5f);//设置线宽
        dataSet.setCircleRadius(2f);//设置焦点圆心的大小
        dataSet.setHighlightLineWidth(0.5f);//设置点击交点后显示高亮线宽
        dataSet.enableDashedHighlightLine(10f, 5f, 0f);//点击后的高亮线的显示样式
        dataSet.setValueTextSize(12f);//设置显示值的文字大小
        dataSet.setDrawFilled(false);//设置使用 范围背景填充
        dataSet.setDrawValues(false);
        dataSet.setDrawCircles(false);
        dataSet.setCircleRadius(5f);//设置外圈圆半径
        dataSet.setCircleColor(getResources().getColor(R.color.colorYellow));//设置外圈圆颜色
        dataSet.setCircleHoleRadius(4f);//设置内圈圆半径
        dataSet.setCircleColorHole(getResources().getColor(R.color.colorWhite));//设置内圈圆颜色
        mLineChart.setScaleXEnabled(false);
        mLineChart.setScaleYEnabled(false);
        CustomMarkerView mv = new CustomMarkerView(getActivity(), R.layout.item_markview);
        mv.setChartView(mLineChart);
        mLineChart.setMarker(mv);


        //X轴与Y轴的样式
        //设置样式
        YAxis rightAxis = mLineChart.getAxisRight();

        //设置图表右边的y轴禁用
        rightAxis.setEnabled(false);
        YAxis leftAxis = mLineChart.getAxisLeft();
        //设置图表左边的y轴禁用
        leftAxis.setEnabled(false);

        //设置x轴
        XAxis xAxis = mLineChart.getXAxis();
        xAxis.setTextColor(Color.parseColor("#333333"));
        xAxis.setTextSize(11f);
        xAxis.setAxisMinimum(0f);
        xAxis.setDrawAxisLine(true);//是否绘制轴线
        xAxis.setDrawGridLines(false);//设置x轴上每个点对应的线
        xAxis.setDrawLabels(true);//绘制标签  指x轴上的对应数值
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置x轴的显示位置
        xAxis.setGranularity(1f);//禁止放大后x轴标签重绘
        xAxis.setLabelCount(12, true);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return String.valueOf((int) value + 1).concat("月");
            }

            @Override
            public int getDecimalDigits() {
                return 0;
            }
        });

        /**
         * 透明化图例
         */
        Legend legend = mLineChart.getLegend();
        legend.setForm(Legend.LegendForm.NONE);
        legend.setTextColor(Color.WHITE);

        /**
         * 隐藏x轴描述
         */
        Description description = new Description();
        description.setEnabled(false);
        mLineChart.setDescription(description);


        //设置数据，刷新列表
        LineData lineData = new LineData(dataSet);
        //是否绘制线条上的文字
        lineData.setDrawValues(false);
        mLineChart.setData(lineData);
        mLineChart.invalidate(); // refresh

    }


}
